import { Models } from '@/common/typings/modle'
import { Buffer } from '@/core/HttpException'
import ExcelJs from 'exceljs'
import fs from 'fs'
import path from 'path'

const commonExportTemplate = (options: any) => async (ctx: Models.Ctx) => {
  // 生成 excel
  const workbook = new ExcelJs.Workbook()
  const worksheet = workbook.addWorksheet(options.fileName)
  worksheet.columns = options.excelColumns
  worksheet.addRow(options.templateData)
  const fileName = `${options.fileName}模板.xlsx`
  const filePath = path.resolve(__dirname, fileName)
  try {
    fs.unlinkSync(filePath)
  } catch (e) {}
  await workbook.xlsx.writeFile(filePath)
  // todo 读取文件 并以流的形式返回
  const stream = fs.createReadStream(filePath)
  // 流返回后将文件删除
  setTimeout(() => {
    try {
      fs.unlinkSync(filePath)
    } catch (e) {}
  })
  throw new Buffer({ data: stream })
}
export default commonExportTemplate
